/**
 * 相关文件关联 
 * @author kaige
 * @date 2022-6-27
 * 说明：依赖 js/files.js  layuiextend/kaige.js扩展
 **/
layui.config({
    base: szoa.client.path + '/static/kaige/layuiextend/'
}).define(['layer', 'form', 'table', 'laytpl', 'kaige'], function (exports) {
    var MOD_NAME = 'glfiles', $ = layui.jquery, kaige = layui.kaige, form = layui.form, table = layui.table, layer = layui.layer, laytpl = layui.laytpl;
    glfiles = function () { };

    glfiles.prototype.form = function (e) {
        var t = this;
        var elem = $('#' + e.id + "_files_gl_html");
        if (e.id == undefined || elem.length < 1) {
            layer.msg('缺少dom');
            return false;
        }
        e.label = typeof(e.label) === 'boolean' ? e.label : true;
        var shtml = '';
        if(e.label){
            shtml +='<label class="layui-form-label">相关文件</label><div class="layui-input-block">';
        }
        shtml += '<ul class="flow-default file_show_box" id="'+ e.id + '_file_show_box"></ul>\
          <div>\
            <button type="button" class="layui-btn layui-btn-sm layui-bg-blue" id="'+ e.id + '_add_file_btn">\
              <i class="layui-icon layui-icon-file"></i>添加文件\
            </button>\
            <input type="hidden" name="'+ e.id + '_files_id" value="">';
        if(e.label) shtml +='</div></div>';
        elem.append(shtml);
        $('#' + e.id + '_add_file_btn').on('click', function (ev) {
            if (!t.yn_addfile(e.id)) {
                layer.msg('最多只能添加5个文件');
                layer.close(window.file_win_layid);
                return false;
            }
            window.file_win_layid = layer.open({
                type: 2,
                title: '<i class="fa fa-upload"></i> 上传文件',
                shade: 0.5,
                area: ['90%', '90%'],
                content: szoa.client.path + '/pages/files/upfiles.html?id=7',
                success: function (layero, index) {
                    window.file_info = function (opt) {
                        if (opt) {
                            t.up_file_additem(e.id, {
                                id: opt.id,
                                url: opt.url,
                                type: opt.type == '2' ? 2 : 1,
                                name: opt.other.name,
                                is_edit: e.is_edit
                            });
                            layer.close(window.file_win_layid);
                        }
                    };
                }
            });
        });
        setTimeout(function () {
            t.edit_init(e.id, {
                is_edit: e.is_edit,
                data: e.data,
                downurl: e.downurl
            });
            (typeof e.callback === 'function') && e.callback();
        }, 50);
    };

    //是否还可以添加文件
    glfiles.prototype.yn_addfile = function (id) {
        var obj = $('#' + id + '_file_show_box');
        if (obj.find('li').length >= 5) {
            return false;
        }
        return true;
    }

    glfiles.prototype.downfile = function (file_id,filename) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", szoa.client.url + szoa.client.module + '/files/down?id=' + file_id);
        xhr.responseType = "blob";
        xhr.setRequestHeader("Kg-Appid", szoa.client.appid);
        xhr.setRequestHeader("Kg-Token", szoa.getToken());
        // xhr.withCredentials = true;//跨域
        xhr.onreadystatechange = () => {
            if (xhr.readyState === xhr.DONE) {
                if (xhr.status === 200) {
                    var aa = document.createElement('a');
                    aa.href = URL.createObjectURL(xhr.response);
                    aa.innerHTML = 'aaa';
                    aa.download = filename;
                    aa.style.display = 'none'; //隐藏a标签 直接调用a标签的点击事件
                    document.body.appendChild(aa);
                    aa.click();
                    // iframe.src = URL.createObjectURL(xhr.response);
                }
            }
        };
        xhr.send();
    }

    //相关文件渲染区-加文件
    glfiles.prototype.up_file_additem = function (id, opt) {
        if (opt == undefined || opt.id == undefined) {
            return false;
        }
        var that = this;
        var obj = $('#' + id + '_file_show_box');
        if (!that.yn_addfile(id)) {
            layer.msg('最多只能添加5个文件');
            return;
        }
        if ($('#' + id + '_ufview_' + opt.id).length > 0) {
            layer.msg('相同的已存在');
            return;
        }
        var shtml = '<li id="' + id + '_ufview_' + opt.id + '" data-id="' + opt.id + '" data-url="' + opt.url + '" style="' + (opt.type == 2 ? 'background-image:url(' + opt.url + ');' : '') + '">';
        if (opt.type == 1) {
            shtml += '<i class="fa fa-file ifont1"></i>';
        }
        if (opt.is_edit) {
            shtml += '<i class="fa fa-window-close iclose"></i>';
        }
        if (opt.type == 1) {
            shtml += '<span class="txt">' + opt.name + '</span>';
        }
        shtml += '<a class="layui-btn layui-btn-xs layui-bg-orange sl-btn">下载</a>';

        //if (opt.type == 2) {
        shtml += '<a class="layui-btn layui-btn-xs layui-bg-blue sr-btn">预览</a>';
        //}
        shtml += '</li>';
        obj.append(shtml);

        var liobj = $('#' + id + '_ufview_' + opt.id);
        //添加文件
        that.add_files_id(id, opt.id);
        //右上角 删除btn
        liobj.find('i.iclose').on('click', function (ev) {
            var files_id = liobj.attr('data-id');
            layer.confirm('确认删除吗？', {
                title: '<i class="layui-icon layui-icon-delete"></i> 删除确认',
                btn: ['确认', '取消']
            }, function (index) {
                that.del_files_id(id, files_id);
                liobj.remove();
                layer.close(index);
            });
        });

        liobj.find('a.sl-btn').on('click', function (ev) {
            var obj = $(this).parent();
            var uid = obj.attr('data-id');
            var url = obj.attr('data-url');
            if(url){
                //获取最后一个/的位置
                var site = url.lastIndexOf("\/");
                //截取最后一个/后的值
                filename = url.substring(site + 1, url.length);
            }
            layer.msg('开始下载', { time: 5000 });
            that.downfile(uid,filename);
        });

        liobj.find('a.sr-btn').on('click', function (ev) {
            if (opt.type == 2) kaige.viewimage({ maxwidth: 600, maxheight: 600, url: opt.url });
            if (opt.type == 1) {
                viewFiles(opt);
            }
        });
    }

    //编辑、查看时 自动渲染 t=true edit,t=false look.后端：files_path 与 files_id 两个数组下标要对应
    glfiles.prototype.edit_init = function (id, e) {
        var that = this;
        if (!e.is_edit) {
            $('#' + id + '_add_file_btn').hide();
        }
        var list = typeof (e.data) === 'string' ? JSON.parse(e.data) : e.data;
        if (typeof (list) === 'object' && list.length > 0) {
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                that.up_file_additem(id, {
                    id: item.id,
                    url: item.url,
                    type: item.type,
                    name: item.name,
                    is_edit: e.is_edit,
                    downurl: e.downurl
                });
            };
        }
    }

    //添加文件ID-表单
    glfiles.prototype.add_files_id = function (id, h) {
        var e = $("input[name=" + id + "_files_id]");
        var d = e.val();
        if (d != undefined && d != null && d != '') {
            var s = d.split(',');
            s.push(h);
            r = s.toString();
            e.val(r);
        } else {
            e.val(h);
        }
    }

    //删除文件ID-表单
    glfiles.prototype.del_files_id = function (eid, id) {
        var e = $("input[name=" + eid + "_files_id]");
        var d = e.val();
        if (d != undefined && d != null && d != '') {
            var s = d.split(',');
            layui.each(s, function (i, item) {
                if (item == id) {
                    s.splice(i, 1);
                }
            });
            r = s.toString();
            e.val(r);
            return true;
        }
        return false;
    }

    var glfiles = new glfiles();
    exports(MOD_NAME, glfiles)
});